﻿using Consul;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;
using Zhaoxi.MicroService.Framework;
using Zhaoxi.MicroService.Interface;
using Zhaoxi.MicroService.Model;
using Zhaoxi.MSAProject.ClientProject.Models;

namespace Zhaoxi.MSAProject.ClientProject.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IUserService _iUserService;

        public HomeController(ILogger<HomeController> logger, IUserService userService)
        {
            _logger = logger;
            this._iUserService = userService;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Info()
        {
            Console.WriteLine($"This is {nameof(HomeController)}.{nameof(Info)}");

            #region 单体架构
            //base.ViewBag.Users = this._iUserService.UserAll();//三层架构---单体架构
            #endregion

            #region 分布式
            //string url = "http://localhost:5726/api/users/all";//5727  5728
            //string content = HttpHelper.InvokeApi(url);
            //base.ViewBag.Users = JsonConvert.DeserializeObject<IEnumerable<User>>(content);
            //Console.WriteLine($"This is {url} Invoke");
            #endregion

            #region Nginx
            //string url = "http://localhost:8086/api/users/all";//Nginx去负载均衡
            //string content = HttpHelper.InvokeApi(url);
            //base.ViewBag.Users = JsonConvert.DeserializeObject<IEnumerable<User>>(content);
            //Console.WriteLine($"This is {url} Invoke");
            #endregion

            #region Consul服务注册发现
            //consul获取服务--得知道ZhaoxiService---api/users/all也得知道
            string url = null;
            url = "http://ZhaoxiService/api/users/all";//consul就像dns--只是负责解析ip：port--清单

            ConsulClient client = new ConsulClient(c =>
            {
                c.Address = new Uri("http://localhost:8500/");
                c.Datacenter = "dc1";
            });//找到consul--像DNS
            var response = client.Agent.Services().Result.Response;//获取服务清单

            Uri uri = new Uri(url);
            string groupName = uri.Host;
            AgentService agentService = null;
            var dictionary = response.Where(s => s.Value.Service.Equals(groupName, StringComparison.OrdinalIgnoreCase)).ToArray();

            {
                //agentService = dictionary[0].Value;//写死第一个  死薅羊毛--没有策略
            }
            {
                //轮询策略 也是平均，但是太僵硬了
                agentService = dictionary[iIndex++ % dictionary.Length].Value;
            }
            {
                ////平均策略--随机获取索引--相对就平均
                //agentService = dictionary[new Random(iIndex++).Next(0, dictionary.Length)].Value;
            }
            {
                ////权重：3个实例能力不同，承担的压力也要不同
                //List<KeyValuePair<string, AgentService>> pairsList = new List<KeyValuePair<string, AgentService>>();
                //foreach (var pair in dictionary)
                //{
                //    int count = int.Parse(pair.Value.Tags?[0]);//1   5   10
                //    for (int i = 0; i < count; i++)
                //    {
                //        pairsList.Add(pair);
                //    }
                //}
                ////16个  
                //agentService = pairsList.ToArray()[new Random(iIndex++).Next(0, pairsList.Count())].Value;
            }

            url = $"{uri.Scheme}://{agentService.Address}:{agentService.Port}{uri.PathAndQuery}";
            string content = HttpHelper.InvokeApi(url);
            base.ViewBag.Users = JsonConvert.DeserializeObject<IEnumerable<User>>(content);
            Console.WriteLine($"This is {url} Invoke");
            #endregion
            return View();
        }

        private static int iIndex = 0;//暂不考虑线程安全

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}